package com.csu.cphone.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csu.common.exception.WebException;
import com.csu.common.vo.ResultVo;
import com.csu.cphone.constants.ErrorCode;
import com.csu.cphone.pojo.CityPojo;
import com.csu.cphone.pojo.CustomerPojo;
import com.csu.cphone.pojo.ProducerPojo;
import com.csu.cphone.service.CustomerService;
import com.csu.cphone.service.LoactionService;
import com.csu.cphone.service.ProducerService;
import com.csu.cphone.service.UserService;
import com.csu.cphone.vo.AdressVo;
import com.csu.cphone.vo.OrderMessageVo;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

/**
 * @项目名称：cphone
 * @类名称：RecycleController
 * @类描述：
 * @创建人：Tangc
 * @创建时间：2017年9月4日 上午10:37:18
 * @company:步步高教育电子有限公司
 */
@Controller
@RequestMapping("/user")
@Api(value = "base", description = "基础信息")
public class UserController
{

    @Autowired
    private UserService userService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ProducerService producerService;

    @Autowired
    private LoactionService loactionService;

    private static final Logger logger = Logger.getLogger(UserController.class);

    @ResponseBody
    @ApiOperation(value = "获取openid", notes = "用户页面引入后跳转,获取openid")
    @RequestMapping(value = "access/callback", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<String> accessUrl(HttpServletRequest request,
            @ApiParam(value = "code") @RequestParam(required = true, value = "code") String code,
            @ApiParam(value = "state") @RequestParam(required = false, value = "state") String state)
            throws WebException
    {

        logger.info("回调成功，code：" + code);

        ResultVo<String> result = new ResultVo<String>();
        String openid = userService.getOpenIdByCode(code, state);
        result.setData(openid);
        return result;
    }

    /*
     * @ResponseBody
     * 
     * @ApiOperation(value = "更新用户openid", notes = "如果用户信息没有openid，需要马上更新")
     * 
     * @RequestMapping(value = "customer/update/{customerId}/{openid}", method =
     * { RequestMethod.POST, RequestMethod.GET }, produces = {
     * "application/json; charset=utf-8" }) public ResultVo<Integer>
     * updateOpenid(HttpServletRequest request,
     * 
     * @ApiParam(value = "openid") @PathVariable(value = "openid") String
     * openid,
     * 
     * @ApiParam(value = "customerId") @PathVariable(value = "customerId")
     * Integer customerId) throws WebException { ResultVo<Integer> resultVo =
     * new ResultVo<Integer>(); Integer result =
     * userService.updateOpenid(openid, customerId); resultVo.setData(result);
     * return resultVo; }
     */

    @ResponseBody
    @ApiOperation(value = "查询用户是否注册", notes = "查询用户是否注册openid")
    @RequestMapping(value = "customer/{openid}", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<CustomerPojo> selectByOpenId(HttpServletRequest request,
            @ApiParam(value = "openid") @PathVariable(value = "openid") String openid) throws WebException
    {
        ResultVo<CustomerPojo> resultVo = new ResultVo<CustomerPojo>();
        CustomerPojo result = userService.selectByOpenId(openid);
        resultVo.setData(result);
        return resultVo;
    }

    @ResponseBody
    @ApiOperation(value = "发送注册短信验证码", notes = "验证码通过短信发送，成功返回success")
    @RequestMapping(value = "sendSignCode/{number}", method = RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    public ResultVo<Boolean> sendSignCode(HttpServletRequest request,
            @ApiParam(value = "电话号码") @PathVariable(value = "number") String number) throws WebException
    {
        ResultVo<Boolean> result = new ResultVo<Boolean>();
        Boolean send = userService.sendSignCode(number);
        result.setData(send);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "客户注册", notes = "校验注册参数，成功后返回用户信息")
    @RequestMapping(value = "customer/sign", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<CustomerPojo> customerSign(HttpServletRequest request,
            @ApiParam(value = "微信openid") @RequestParam(value = "wxOpenid", required = false) String wxOpenid,
            @ApiParam(value = "登录密码") @RequestParam(value = "password", required = true) String password,
            @ApiParam(value = "电话号码") @RequestParam(value = "number", required = true) String number,
            @ApiParam(value = "名称") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "验证码") @RequestParam(value = "authCode", required = true) String authCode)
            throws WebException
    {
        if (password == null || "".equals(password.trim()) || (number == null || "".equals(number.trim())))
        {
            // 参数不能为空
            throw new WebException(ErrorCode.ParamNullCode, ErrorCode.ParamNullMessgae);
        }

        ResultVo<CustomerPojo> result = new ResultVo<CustomerPojo>();

        // 验证码校验
        userService.checkAuthCode(number, authCode);

        // 登录操作
        CustomerPojo customer = userService.customerSign(wxOpenid, number, password, name);

        result.setData(customer);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "客户登录", notes = "登录校验，成功后返回用户信息")
    @RequestMapping(value = "customer/login", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<CustomerPojo> customerLogin(HttpServletRequest request,
            @ApiParam(value = "微信openid") @RequestParam(value = "wxOpenid", required = true) String wxOpenid,
            @ApiParam(value = "登录密码") @RequestParam(value = "password", required = true) String password,
            @ApiParam(value = "电话号码") @RequestParam(value = "number", required = false) String number)
            throws WebException
    {
        if (wxOpenid == null && number == null)
        {
            // 微信id和电话号码不能同时为空
            throw new WebException(ErrorCode.LoginParamErrorCode, ErrorCode.LoginParamErrorMessgae);
        }
        if (password == null)
        {
            // 参数不能为空
            throw new WebException(ErrorCode.ParamNullCode, ErrorCode.ParamNullMessgae);
        }

        ResultVo<CustomerPojo> result = new ResultVo<CustomerPojo>();

        // 登录操作
        CustomerPojo customer = userService.customerLogin(wxOpenid, number, password);

        result.setData(customer);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "查询用户信息", notes = "用户信息")
    @RequestMapping(value = "/customerInfo/{customerId}", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<CustomerPojo> customerInfo(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "用户id") @PathVariable(value = "customerId", required = true) Integer customerId)
    {

        ResultVo<CustomerPojo> resultVo = new ResultVo<CustomerPojo>();
        // 添加
        CustomerPojo result = customerService.queryById(customerId);
        resultVo.setData(result);

        return resultVo;
    }

    @ResponseBody
    @ApiOperation(value = "服务方登录", notes = "登录校验，成功后返回用户信息")
    @RequestMapping(value = "producer/login", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<ProducerPojo> producerLogin(HttpServletRequest request,
            @ApiParam(value = "登录密码") @RequestParam(value = "password", required = true) String password,
            @ApiParam(value = "电话号码") @RequestParam(value = "number", required = true) String number)
            throws WebException
    {
        if (number == null || password == null)
        {
            // 参数不能为空
            throw new WebException(ErrorCode.ParamNullCode, ErrorCode.ParamNullMessgae);
        }

        ResultVo<ProducerPojo> result = new ResultVo<ProducerPojo>();

        // 登录操作
        ProducerPojo producer = userService.producerLogin(number, password);

        result.setData(producer);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "查询服务方信息", notes = "服务方信息")
    @RequestMapping(value = "/producerInfo/{producerId}", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<ProducerPojo> producerInfo(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "服务方id") @PathVariable(value = "producerId", required = true) Integer producerId)
    {

        ResultVo<ProducerPojo> resultVo = new ResultVo<ProducerPojo>();
        // 添加
        ProducerPojo result = producerService.queryById(producerId);
        resultVo.setData(result);

        return resultVo;
    }

    @ResponseBody
    @ApiOperation(value = "通过手机号码查询服务方信息", notes = "通过手机号码查询服务方信息")
    @RequestMapping(value = "/producerInfoByNumber/{number}", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<ProducerPojo> producerInfoByNumber(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "手机号码") @PathVariable(value = "number", required = true) String number)
    {

        ResultVo<ProducerPojo> resultVo = new ResultVo<ProducerPojo>();
        // 添加
        ProducerPojo result = userService.getProducerByNumber(number);
        resultVo.setData(result);

        return resultVo;
    }

    @ResponseBody
    @ApiOperation(value = "服务方上报", notes = "登录后上报一下位置，以便派单;需要修改状态也调用这个")
    @RequestMapping(value = "producer/upload", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<List<OrderMessageVo>> producerUpload(
            HttpServletRequest request,
            @ApiParam(value = "电话号码") @RequestParam(value = "number", required = true) String number,
            @ApiParam(value = "纬度") @RequestParam(value = "lat", required = true) Double lat,
            @ApiParam(value = "经度") @RequestParam(value = "lng", required = true) Double lng,
            @ApiParam(value = "上门服务状态：0停止服务，1正常服务") @RequestParam(value = "serviceStatus", required = false) Integer serviceStatus)
            throws WebException
    {

        ResultVo<List<OrderMessageVo>> result = new ResultVo<List<OrderMessageVo>>();

        List<OrderMessageVo> messages = userService.producerUpload(number, lat, lng, serviceStatus);

        result.setData(messages);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "上报频率", notes = "获取上报频率，单位min")
    @RequestMapping(value = "uploadFrequency", method = RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    public ResultVo<Integer> uploadFrequency(HttpServletRequest request) throws WebException
    {
        ResultVo<Integer> result = new ResultVo<Integer>();
        // 每隔多久上报一次，单位min
        result.setData(3);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "服务方获取上门服务状态", notes = "获取上门状态")
    @RequestMapping(value = "producer/serviceStatus/{number}", method = { RequestMethod.POST, RequestMethod.GET }, produces = { "application/json; charset=utf-8" })
    public ResultVo<Integer> serviceStatus(HttpServletRequest request,
            @ApiParam(value = "电话号码") @PathVariable(value = "number", required = true) String number)
            throws WebException
    {

        ResultVo<Integer> result = new ResultVo<Integer>();

        // 登录操作
        Integer status = userService.getServiceStatus(number);

        result.setData(status);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "获取省市信息", notes = "通过定位获取省市信息")
    @RequestMapping(value = "getAddreessByPosition/{lat}/{lng}", method = RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    public ResultVo<AdressVo> getAddreessByPosition(HttpServletRequest request,
            @ApiParam(value = "经度") @PathVariable(value = "lng") double lng,
            @ApiParam(value = "纬度") @PathVariable(value = "lat") double lat) throws WebException
    {
        ResultVo<AdressVo> result = new ResultVo<AdressVo>();

        AdressVo adress = loactionService.getAdreessByPosition(lat, lng);

        result.setData(adress);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "获取省市信息", notes = "通过定位获取省市信息")
    @RequestMapping(value = "getPositionByAddreess/{address}", method = RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    public ResultVo<String> getPositionByAddreess(HttpServletRequest request,
            @ApiParam(value = "详细地址") @PathVariable(value = "address") String address,
            @ApiParam(value = "所属城市") @RequestParam(value = "city", required = false) String city) throws WebException
    {
        ResultVo<String> result = new ResultVo<String>();

        String posiotn = loactionService.getPositionByAddreess(address, city);

        result.setData(posiotn);
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "获取省市集合", notes = "获取所有省市信息")
    @RequestMapping(value = "getAllAddress", method = RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    public ResultVo<List<CityPojo>> getAllAddress(HttpServletRequest request) throws WebException
    {
        ResultVo<List<CityPojo>> result = new ResultVo<List<CityPojo>>();

        List<CityPojo> cityList = loactionService.getCityList();
        result.setData(cityList);
        return result;
    }
}
